package main

import (
	"time"
	"net"
	"log"
	"github.com/bugfan/logrus"
	"go-im-server/models"	
	"github.com/astaxie/beego/orm"
)
const(
	IP="0.0.0.0"
	PORT="9996"
	BUF_SIZE=3			//字节多少都是有可能在接受汉子的实收乱码 暂时未解决
)
var (
	debug=true
	ConnNum=0
	Conns map[string]model.ConnData
)
type LogrusWriter struct {
}

func (self *LogrusWriter) Write(p []byte) (n int, err error) {
	logrus.Infof(string(p))
	return len(p), nil
}
type EmptyWriter struct {
}

func (self *EmptyWriter) Write(p []byte) (n int, err error) {
	// nothing to do
	return len(p), nil
}
func init(){
	if !debug {
		// 不把日志打印到控制台
		logrus.SetOutput(&EmptyWriter{})
		// orm数据库日志输出到logrus日志系统
		orm.DebugLog = orm.NewLog(&LogrusWriter{})
	}
	//1 初始变量
	Conns=make(map[string]model.ConnData,1)
}
func main(){
	l,err:=net.Listen("tcp",":"+PORT)
	if err!=nil{
		log.Fatal(err)
	}
	defer l.Close()
	go ConnStatus()					//打连接信息
	for {
		conn,err:=l.Accept()
		if err!=nil{
			logrus.Errorln(err)
			continue
		}
		ConnNum++
		logrus.Info("a client connected:",conn.RemoteAddr().String(),"|",conn.RemoteAddr().Network(),"|")
		go fuck(conn)
	}
	
}
func fuck(conn net.Conn){
	defer fuckEnd(conn)
	if _,ok:=Conns[conn.RemoteAddr().String()];ok{
		//1 给他发送通知

		//2 删除旧的引用
		delete(Conns,conn.RemoteAddr().String())	
	}
	//3 存新的引用
	o:=model.ConnData{
		Conn:conn,
	}
	Conns[conn.RemoteAddr().String()]=o
	//4 消息循环
	buffer := make([]byte, BUF_SIZE)
	for {
		n, err := conn.Read(buffer)
		if err != nil {
			break
		}
		println("Recei:", conn.RemoteAddr().String(), string(buffer[:n]))
	}
}
func fuckEnd(conn net.Conn){
	if _,ok:=Conns[conn.RemoteAddr().String()];ok{
		//1 给他发送通知

		//2 删除旧的引用
		delete(Conns,conn.RemoteAddr().String())	
	}
	ConnNum--
	conn.Close()
}
func ConnStatus(){
	for{
		time.Sleep(5e9)
		logrus.Println("map length is :",len(Conns),"|conn num is:",ConnNum)			
	}
}